﻿using System;
using System.Collections.ObjectModel;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Data;
using System.Windows.Input;
using RIA.ServicesLibrary.Web.Models;
using RIA.ServicesLibrary.Web.Services;
using SL4.CustomControls;
namespace RIA.ViewModel
{
    public class CustomerListViewModel:ViewModelBase
    {
        #region Member Variables
        private CustomerContext _customerContext = new CustomerContext ();
        private ObservableCollection<Customer> _customerOC = null;
        #endregion
        public CustomerListViewModel ()
        {
            this._customerOC = new ObservableCollection<Customer> ();
            this.DataList = new CustomPagedCollectionView<Customer> ();
            this.DataList.OnRefresh += new EventHandler ( DataList_OnRefresh );
        }

        void DataList_OnRefresh ( object sender, EventArgs e )
        {
            BeginLoadPagedCustomers ( FirstName );
        }


        #region PagedCollectionView
        private PagedCollectionView _pagedView = null;
        public PagedCollectionView PagedView
        {
            get { return this._pagedView; }
            set
            {
                this._pagedView = value;
                OnPropertyChanged ( () => PagedView );
            }
        } 
        #endregion


        #region ObservableCollection
        /// <summary>
        /// ObservableCollection for customer.
        /// </summary>
        public ObservableCollection<Customer> CustomersOC
        {
            get
            {
                return this._customerOC;
            }
        } 
        #endregion

        #region Commands
        public ICommand LoadCustomers
        {
            get
            {
                return new DelegateCommand(BeginLoadCustomers, (o) => true);
            }
        }
       
        public void BeginLoadCustomers(object param)
        {
            string customName = param.ToString ();
            this.IsBusy = true;

            EntityQuery<Customer> qry = _customerContext.GetCustomersQuery();
            qry = qry
                .Where ( c => c.FirstName.Contains ( customName ) || c.LastName.Contains(customName) )
                .OrderBy ( c => c.LastName )
                .ThenBy ( c => c.FirstName );
                
            LoadOperation<Customer> op = _customerContext.Load ( qry,true);
            op.Completed += LoadCustomers_Completed;
        }
        private void LoadCustomers_Completed(object sender, EventArgs e)
        {
            LoadOperation op = sender as LoadOperation;
            this.IsBusy = false;
            if (!op.HasError)
            {
                #region PagedCollectionView
                PagedCollectionView view = new PagedCollectionView ( op.Entities );
                PropertyGroupDescription groupBy = new PropertyGroupDescription ( "FirstName" );
                view.GroupDescriptions.Add ( groupBy );
                this.PagedView = view; 
                #endregion

                #region ObserverCollection
                //this._customerOC.Clear ();
                //foreach ( Customer c in op.Entities )
                //{
                //    this._customerOC.Add ( c );
                //} 
                #endregion
            }
            else
            {
                // Handle this error appropriately - omitted for brevity
                op.MarkErrorAsHandled ();
            }
        }
        #endregion


        #region PagedCommands
            
            /// <summary>
            /// Gets or sets the data list.
            /// </summary>
            /// <value>The data list to data bind ItemsSource.</value>
            public CustomPagedCollectionView<Customer>  DataList { get; private set; }
            /// <summary>
            /// Gets or sets the size of the page.
            /// </summary>
            /// <value>The size of the page.</value>
            public int PageSize
            {
                get
                {
                    return DataList.PageSize;
                }
                set
                {
                    if ( value == DataList.PageSize ) return;
                    DataList.PageSize = value;
                    OnPropertyChanged ( "PageSize" );
                }
            }

            private string _firstName = "";
            public string FirstName
            {
                get { return _firstName; }
                set 
                {
                    this._firstName = value;
                    OnPropertyChanged ( "FirstName" );
                }
            }

            public ICommand LoadPagedCustomers
            {
                get
                {
                    return new DelegateCommand ( BeginLoadPagedCustomers, ( o ) => true );
                }
            }
            public void BeginLoadPagedCustomers ( object param )
            {
                string customName = param.ToString ();
                ShowBusyStatus ();

                EntityQuery<Customer> qry = _customerContext.GetCustomersQuery ();
                int skip = DataList.PageIndex * DataList.PageSize;
                // Add a Where clause to filter the results
                qry = qry
                    .Where ( c => c.FirstName.Contains ( customName ) || c.LastName.Contains ( customName ) )
                    .OrderBy ( x => x.LastName )
                    .Skip ( skip )
                    .Take ( DataList.PageSize );
                qry.IncludeTotalCount = true;
                //Grouping List firt sort the List.
                                  

                LoadOperation<Customer> op = _customerContext.Load ( qry, true );
                op.Completed += ( x, y ) => {
                    HideBusyStatus ();
                    if ( op.HasError )
                    {
                            System.Windows.MessageBox.Show ( op.Error.ToString (), "Load Error",
                            System.Windows.MessageBoxButton.OK );
                            op.MarkErrorAsHandled ();
                    }
                    else
                    {
                        DataList.Clear ();
                        DataList.ItemCount = op.TotalEntityCount;
                        foreach ( Customer c in op.Entities )
                        {
                            DataList.Add ( c );
                        }
                    }
                    
                };
            }
      
        #endregion



    }
         

    
}
